$(function() {

    var automaticAdd = false;

    var currentConnection = null;
    var deletingConnection = null;
    var deletingPlanet = null;

    function htmlEncode(value) {
        if (value) {
            return jQuery('<div />').text(value).html();
        } else {
            return '';
        }
    }

    function htmlDecode(value) {
        if (value) {
            return $('<div />').html(value).text();
        } else {
            return '';
        }
    }

    function getRealIdFromFake(fakeId) {
        var tokens = fakeId.split("-");
        return tokens.pop();
    }

    function findIdPlanetInPlanetObjs(planet) {

        var found = -1;
        $.each(planetsObjs, function(i) {
//            alert(planet + " e' uguale a "+ this.idPlanet + " ?");
            if (this.idPlanet == planet) {
                found = i;
            }
        });
        return found;
    }

    /* Prende in input una stringa tipo #FFFFFF o FFFFFF e ritorna un oggetto cha ha proprietà rbg decimali
     * 
     * @param {String} hex
     * @returns Una struttura con proprietà r, g, b. Ognuna rappresentante la proprietà del colore.
     */
    function hexToRgb(hex) {
        // nel caso venga passato il cancelletto lo elimina dalla stringa
        hex.replace("#", "");
        // Espande la forma a triplete (tipo "03F") nella forma estesa (analogamente "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    /* Traduce un componente decimale in HEX
     * 
     * @param {String} c
     * @returns {String}
     */
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }

    /* Prende in input i valori RGB e ritorna una stringa in esadecimale tipo #FFFFFF
     * 
     * @param {String} r
     * @param {String} g
     * @param {String} b
     * @returns {String} tipo #FFFFFF
     */
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }

    connections = [],
            updateConnections = function(conn) {
        // metto in un array globale

        if (connections.length > 0) {
            //connections = connections.sort();
            console.log("Connection NON VUOTO");
            for (var j = 0; j < connections.length; j++) {
                console.log("check connessione ", connections[j].id);
                if ((conn.sourceId === connections[j].sourceId && conn.targetId === connections[j].targetId) ||
                        (conn.sourceId === connections[j].targetId && conn.targetId === connections[j].sourceId)) {
                    //console.log("Trovate connessioni uguali "+connections[j].id,+" - "+connections[j+1].id);
                    //results.push(connections[j]);
                    return false;
                }

            }
            console.log("Aggiornata lista connessioni: ", conn.id);
            connections.push(conn);


        } else {
            console.log("Connection VUOTO");
            console.log("Aggiornata lista connessioni: ", conn.id);
            connections.push(conn);
        }
        // aggiunta cosa db
        return true;
    };

    $("#color-confirm").click(function() {
        var realSourceId = getRealIdFromFake(currentConnection.sourceId);
        var realTargetId = getRealIdFromFake(currentConnection.targetId);
        var decimalColor = hexToRgb($("#currentColor").val());

//        currentConnection.getOverlay("label").setLabel(decimalColor.r + ", " + decimalColor.g + ", " + decimalColor.b);
        currentConnection.setPaintStyle({
            lineWidth: 3,
            strokeStyle: "rgba(" + decimalColor.r + "," + decimalColor.g + "," + decimalColor.b + ",0.5)",
            joinstyle: "round"
                    //outlineColor:transparent,
                    //outlineWidth:7
        });

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "insert",
            red: decimalColor.r,
            green: decimalColor.g,
            blue: decimalColor.b
        }).done(function(data) {
//            alert("Connessione tra " + realSourceId + " e " + realTargetId + " inserita con colore " + decimalColor.r + ", " + decimalColor.g + ", " + decimalColor.b);
        });

    });
    $("#color-cancel").click(function() {
        var realSourceId = getRealIdFromFake(currentConnection.sourceId);
        var realTargetId = getRealIdFromFake(currentConnection.targetId);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "insert",
            red: 255,
            green: 255,
            blue: 255
        }).done(function(data) {
//            alert("Connessione tra " + realSourceId + " e " + realTargetId + " inserita senza colore ");
        });
    });



    window.jsPlumbDemo = {
        init: function() {

            jsPlumb.importDefaults({
                // default drag options
                DragOptions: {cursor: 'pointer', zIndex: 2000},
                // default to blue at one end and green at the other
                EndpointStyles: [{fillStyle: '#558822'}],
                // blue endpoints 7 px; green endpoints 11.
                Endpoints: [["Dot", {radius: 11}]]
                        // the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
                        // case it returns the 'labelText' member that we set on each connection in the 'init' method below.
//                ConnectionOverlays: [
//                    //[ "Arrow", { location:0.9 } ],
//                    ["Label", {
//                            location: 0.5,
//                            id: "label",
//                            cssClass: "aLabel"
//                        }]
//                ]
            });

            // this is the paint style for the connecting lines..
            var whiteColor = "rgba(255,255,255,0.5)";
            var redColor = "rgba(255, 165, 0,0.5)";
            var transparent = "rgba(0, 0, 0,0)";
            var connectorPaintStyle = {
                lineWidth: 3,
                strokeStyle: whiteColor,
                joinstyle: "round",
                //outlineColor:transparent,
                //outlineWidth:7
            },
                    // .. and this is the hover style. 
                    connectorHoverStyle = {
                lineWidth: 3,
                strokeStyle: redColor
            },
            // the definition of source endpoints (the small blue ones)
            sourceEndpoint = {
                endpoint: "Dot",
                paintStyle: {fillStyle: whiteColor, radius: 15},
                isSource: true,
                isTarget: true,
                connector: ["Straight", /*{ stub:[40, 60], gap:10 }*/],
                connectorStyle: connectorPaintStyle,
                //hoverPaintStyle:connectorHoverStyle,
                connectorHoverStyle: connectorHoverStyle,
                dragOptions: {},
                beforeDrop: function(params) {
                    return updateConnections(params.connection);
                },
                maxConnections: -1
            },
            // a source endpoint that sits at BottomCenter
            //	bottomSource = jsPlumb.extend( { anchor:"BottomCenter" }, sourceEndpoint),
            // the definition of target endpoints (will appear when the user drags a connection) 
            targetEndpoint = {
                endpoint: "Dot",
                paintStyle: {fillStyle: "#558822", radius: 11},
                hoverPaintStyle: connectorHoverStyle,
                maxConnections: -1,
                dropOptions: {hoverClass: "hover", activeClass: "activeConn"},
                isTarget: true
//                overlays: [
//                    ["Label", {location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel"}]
//                ]
            };
            // init = function(connection) {



            // var text = prompt("Ragione connessione",connection.id);
            // if(text == null){
            // text = "";
            // connection.getOverlay("label").hide();
            // } 
            // connection.getOverlay("label").setLabel(text);
// 				
            // connection.bind("editCompleted", function(o) {
            // if (typeof console != "undefined")
            // console.log("connection edited. path is now ", o.path);
            // });


            // };			

            var allSourceEndpoints = [];
            _addEndpoints = function(toId, sourceAnchors, targetAnchors) {
                for (var i = 0; i < sourceAnchors.length; i++) {
                    var sourceUUID = toId + sourceAnchors[i];
                    allSourceEndpoints.push(jsPlumb.addEndpoint(toId, sourceEndpoint, {anchor: sourceAnchors[i], uuid: sourceUUID}));
                }
                /*
                 for (var j = 0; j < targetAnchors.length; j++) {
                 var targetUUID = toId + targetAnchors[j];
                 allTargetEndpoints.push(jsPlumb.addEndpoint(toId, targetEndpoint, { anchor:targetAnchors[j], uuid:targetUUID }));						
                 }*/
            };


//            _addEndpoints("endpoint-36", ["TopCenter"]);

            // listen for new connections; initialise them the same way we initialise the connections at startup.
            jsPlumb.bind("jsPlumbConnection", function(connInfo, originalEvent) {
                init(connInfo.connection);
            });

            // make all the window divs draggable						
            jsPlumb.draggable(jsPlumb.getSelector("div.window"), {
                stop: function() {
                    var planetId = getRealIdFromFake($(this).attr("id"));
                    var x = $(this).css("left").replace("px", "");
                    var y = $(this).css("top").replace("px", "");

                    $.post("/connectionsServlet", {
                        planetMoved: planetId,
                        setX: x,
                        setY: y
                    }).done(function(data) {
//                        alert("Aggiornata posizione sul db di: " + planetId + " con punto " + x + ", " + y);
                    });
                }
            });



            //
            // listen for clicks on connections, and offer to delete connections on click.
            //
            jsPlumb.bind("click", function(conn, originalEvent) {
//                alert(conn.getType());
                // conn.setType();
                deletingConnection = conn;
                conn.strokeStyle = 'rgba(0,255,0,0.7)';
                conn.repaint();

                var sourcePlanet = $("#" + conn.sourceId).attr("title");
                var destPlanet = $("#" + conn.targetId).attr("title");

                $("#myModalLabel2").text("Conferma eliminazione");
                $("#myModal2 .modal-body p").text("Vuoi cancellare la connessione tra il pianeta " + sourcePlanet + " e " + destPlanet + " ?");
                $('#myModal2').modal('show');





            });

            jsPlumb.bind("connectionDrag", function(connection) {
                console.log("Inizio a tracciare " + connection.id);
            });

            jsPlumb.bind("connectionDragStop", function(connection) {
                console.log("Connessione " + connection.id + " tracciata e posizionata");

            });

            jsPlumb.bind("connection", function(info, originalEvent) {
                //updateConnections(info.connection);

                currentConnection = info.connection;

                if (!automaticAdd) { // flag che permette di sapere se sono connesisoni aggiunte dal server o dall'utente
                    $("#connectionModalLabel").text("Scegli un colore della connessione");
                    $('#connectionModal').modal('show');
                }
//                alert(info.connection.id);

            });
        }
    };

    $("#delete-conn-confirm").click(function() {

        var realSourceId = getRealIdFromFake(deletingConnection.sourceId);
        var realTargetId = getRealIdFromFake(deletingConnection.targetId);

        $.post("/connectionsServlet", {
            startPlanet: realSourceId,
            endPlanet: realTargetId,
            actionToDo: "delete"
        }).done(function(data) {
//            alert("Connessione tra " + realSourceId + " e " + realTargetId + " eliminata");
        });

        jsPlumb.detach(deletingConnection);
        connections.splice(connections.indexOf(deletingConnection)); // rimuove dalla lista connessioni
    });


    var globalIdPlanet;
    var currentActiveTab;
    var planetsArray = [];
    var globalIdUniverse = $("#universe_id").attr("data-id");

    var planetSelected = false;

    /** Gestione delle tab **/
    $('#myTab .active a').tab('show');
    $('#planetTabLv1 .active a').tab('show');
    // titolo dinamico

    $('.nav-tabs a').on('shown', function(e) {
        var currentId = $(this).attr('id');
//        currentActiveTab = currentId;
        $(".creation-titles .active").removeClass("active");
        var currentElem = $("#title-" + currentId);
        currentElem.addClass("active");

        if (currentElem.attr("id") === "title-tab-step1") {

        }
    });

    /* Prende in input una stringa tipo #FFFFFF o FFFFFF e ritorna un oggetto cha ha proprietà rbg decimali
     * 
     * @param {String} hex
     * @returns Una struttura con proprietà r, g, b. Ognuna rappresentante la proprietà del colore.
     */
    function hexToRgb(hex) {
        // nel caso venga passato il cancelletto lo elimina dalla stringa
        hex.replace("#", "");
        // Espande la forma a triplete (tipo "03F") nella forma estesa (analogamente "0033FF")
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function(m, r, g, b) {
            return r + r + g + g + b + b;
        });

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    /* Traduce un componente decimale in HEX
     * 
     * @param {String} c
     * @returns {String}
     */
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }

    /* Prende in input i valori RGB e ritorna una stringa in esadecimale tipo #FFFFFF
     * 
     * @param {String} r
     * @param {String} g
     * @param {String} b
     * @returns {String} tipo #FFFFFF
     */
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }

    function getType(tabId) {
        if (tabId === "tab-step231-happy" ||
                tabId === "tab-step233-sad" ||
                tabId === "tab-step231") {
            // è immagine
            return "image";
        } else {
            // è multimedia
            return "multimedia";
        }
    }

    function getHappinessFromTabId(tabId) {
        if (tabId.indexOf("-sad") == -1) { // felice
//            alert(tabId+": tab Felice");
            return 1;
        } else { // triste
//            alert(tabId+": tab Triste");
            return 0;
        }
    }

    function checkContentDescAndSend(real, tabObj, async) {

        var that = tabObj;

        if (!real) {
            that = "#" + currentActiveTab;
        }

        currentContentId = $("#" + currentActiveTab).attr("href");

        descriptionText = $(currentContentId + " textarea").val();
        titleText = $(currentContentId + " input.input-title").val();
        var savedType = getType(currentActiveTab);

        if (checkContentDescription(currentContentId, savedType) === false)
            return false;

        $.ajax({
            async: async,
            type: 'POST',
            data: {happiness: getHappinessFromTabId(currentActiveTab),
                description: descriptionText,
                title: titleText,
                type: savedType
            },
            url: '/manageDescriptionServlet'
        }).done(function(data) {
//            alert("description salvata: " + descriptionText + "tipo collection: " + savedType + " | "+happynessCurrent+", "+descriptionText+", "+titleText+", "+savedType+" | GET: "+getHappinessFromTabId($(that).attr('id')));
        });
        var gettingType = getType($(that).attr('id'));

        // ottengo la descrizione del contenuto, in caso di multimedia anche del titolo
        $.ajax({
            async: async,
            type: 'GET',
            data: {happiness: getHappinessFromTabId($(that).attr('id')),
                type: gettingType
            },
            url: '/manageDescriptionServlet'
        }).done(function(data) {
            var gettedContentId = $("#" + $(that).attr('id')).attr("href");
//            alert("ID: " + gettedContentId);
            var obj = $.parseJSON(data);
            $(gettedContentId + " textarea").val(obj['desc']);

            if ($(gettedContentId + " input.input-title").length)
                $(gettedContentId + " input.input-title").val(obj['title']);

//            alert("!description ottenuta: " + data + "tipo collection: " + gettingType);
        });

        currentActiveTab = $(that).attr('id');
    }

    $("#planetTabLv2-emotional li a, #planetTabLv2 li a").click(function() {
        if (checkContentDescAndSend(true, this, true) !== false)
            return true;
        return false;

    });

    function checkContentDescription(currentContentId, type) {
        var validated = true;
        var rawDescriptionText = $(currentContentId + " textarea").val();
        var descriptionText = rawDescriptionText;//.replace(" ","");
        var titleText = $(currentContentId + " input.input-title").val();
        // resetta gli errori
        $(currentContentId + " textarea").parent().find(".help-block").fadeOut();
        $(currentContentId + " input.input-title").parent().find(".help-block").fadeOut();
        $(currentContentId + " textarea").parent().parent().removeClass("error");
        $(currentContentId + " input.input-title").parent().parent().removeClass("error");
//        alert(currentContentId + " ->"+ $(currentContentId + " .template-download").length + " desc: "+descriptionText + " | lunga: "+descriptionText.length); // non salva 
        if ($(currentContentId + " .template-download").length > 0) {
//            alert("Ci sono immagini");
            if (descriptionText.length < 3) {
//                alert("decrizione vuota");
                $(currentContentId + " textarea").parent().parent().addClass("error");
                $(currentContentId + " textarea").parent().find(".help-block").fadeIn();
                $('html, body').animate({
                    scrollTop: $(currentContentId + " textarea").offset().top
                }, 2000);
                validated = false;
            }
            if (type === "multimedia" && titleText.length < 3) {
                $(currentContentId + " input.input-title").parent().parent().addClass("error");
                $(currentContentId + " input.input-title").parent().find(".help-block").fadeIn();
                validated = false;
            }
        }
//        alert(validated);
        return validated;
    }
    /** Nascondo le sottotab della gestione dei contenuti tristi **/


    /** Gestione dei form/hints **/

    // suggerimento per l'avatar autogenerato

//    $("#universe-avatar-img").click(function(e) {
//        e.preventDefault();
//        $(this).popover();
//    });

    $("#universe-avatar-img").tooltip({title: "L'immagine dell'universo verrà generata in automatico appena si saranno inserite le prime tre immagini nei pianeti"});
    if ($("#universe-avatar-img img").length) {
        $.get("/AvatarManagerServlet", {
        }).done(function(path) {
            if (path !== "") {
                $("#universe-avatar-img img").attr("src", path);
                if (path.indexOf("no-avatar") === -1) {
                    $("#universe-avatar-img").tooltip("destroy");
//                    $("#universe-avatar-img").tooltip({title: "Se non ti piace l'immagine dell'universo...FOTTITI!"});
                }

            }
        });
    }
    /* step 1 - universo */
    $("#nameUniverse-container input:text, #descUniverse-container textarea").focusout(function() {
        checkField(this);
    });
    $("#descUniverse-container textarea").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno l'universo"
    });

    /* step 2/2 - informazioni pianeta */

    $("#descPlanet").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno il pianeta"
    });

    $("#descImageSet-happy").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno la parte <strong>immagini felici</strong> del pianeta"
    });
    $("#descImageSet-sad").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno la parte <strong>immagini non felici</strong> del pianeta"
    });
    $("#descMultimediaSet-happy").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno la parte <strong>video/audio felice</strong> del pianeta"
    });
    $("#descMultimediaSet-sad").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno la parte <strong>video/audio non felice</strong> del pianeta"
    });
    $("#descImageSet").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno la parte <strong>immagini</strong> del pianeta"
    });
    $("#descMultimediaSet").tooltip({
        html: true,
        delay: {show: 1500, hide: 0},
        title: "<span class=\"info-desc\"></span> Quello che inserirai in questa area rappresenta le informazioni che accompagneranno la parte <strong>video/audio</strong> del pianeta"
    });


    /* vuole in input in input:text / textarea */
    function checkField(field) {
        var checked = true;
        hideErrorToContainer($(field).parent().parent());
        if ($(field).val().length < 2) {
            checked = false;
            showErrorToContainer($(field).parent().parent());
        }
        return checked;
    }

    function checkFirstStepFields() {
        var checked = true;
        var nameContainer = $("#nameUniverse-container");
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        /*if(nameContainer.find("input:text").val().length < 2){
         checked = false;
         showErrorToContainer(nameContainer);
         }*/
        nameContainer = $("#descUniverse-container");
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("textarea")))
            checked = false;
        /*if(nameContainer.find("textarea").val().length < 2){
         checked = false;
         showErrorToContainer(nameContainer);
         }*/
        return checked;
    }

    function checkSecondStepFields() {
        var checked = true;
        var nameContainer = $("#firstLine-container"); // primo titolo
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        var nameContainer = $("#secondLine-container"); // secondo titolo
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        var nameContainer = $("#thirdLine-container"); // terzo titolo
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        var nameContainer = $("#labelPlanet-container"); // titolo galassia
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("input:text")))
            checked = false;
        nameContainer = $("#descPlanet-container");
        hideErrorToContainer(nameContainer);
        if (!checkField(nameContainer.find("textarea")))
            checked = false;
        /*if(nameContainer.find("textarea").val().length < 2){
         checked = false;
         showErrorToContainer(nameContainer);
         }*/
        return checked;
    }

    function hideErrorToContainer(nameContainer) {
        $(nameContainer).removeClass("error");
        $('.help-inline', nameContainer).fadeOut("slow");
        $('.help-block', nameContainer).fadeOut("slow");
    }

    function showErrorToContainer(nameContainer) {
        $(nameContainer).addClass("error");
        $('.help-inline', nameContainer).fadeIn("slow");
        $('.help-block', nameContainer).fadeIn("slow");
    }


    $("#first-step-submit").submit(function(event) {
        event.preventDefault();
        $("#tab-step2").click();

    });


    /*$("#add-tag").click(function(e){
     e.preventDefault();
     
     $(this).popover({
     html : true,
     content: function() {
     return $('#popover_content_wrapper').html();
     }
     
     });
     });*/

    var $container;
    var $popover;
    function generatePopover() {

        $popover = $("#add-tag").popover({
            html: true,
            content: function() {
                return $('#popover_content_wrapper').html();
            },
            container: $container,
            trigger: 'manual'

        });

        $popover.on('shown', function() {


        });
    }

    $(this).on("click", ".popover-content a", function(e) {
        e.preventDefault();
        //alert("culo"); // TODO: GESTIONE TAG AGGIUNTA
        $popover.popover('toggle');
        $popover.popover('destroy');
        var newTag = $(this).parent().find("input:text").val();

        $.post("/insertTagServlet", {
            editingPlanetId: globalIdPlanet,
            tagName: newTag
        }).done(function(data) {
//            alert("Tutto Ok:" + data);

            $("#tags-container .controls #add-tag").before("<span id=\"" + data + "\" class=\"badge badge-info\">" + newTag + " <a href=\"#\" class=\"remove-tag\"><i class=\"icon-remove\"></i></a></span>&nbsp;");
            //$("#tags-container .controls #add-tag").before("<span id=\"" + 1 + "\" class=\"badge badge-info\">" + newTag + " <a href=\"#\" class=\"remove-tag\"><i class=\"icon-remove\"></i></a></span>&nbsp;");

        });

        // alert("aggiungi al db il tag: " + newTag);
        // $("#tags-container .controls #add-tag").before("<span class='badge badge-info'>" + newTag + "</span>\n");
    });


    $(this).on("click", "#add-tag", function(e) {
        e.preventDefault();
        // quiiiii
        if(checkSecondStepFields()) {
            sendPlanetData(true, false);
            generatePopover();
            $popover.popover('show');
        }
            // globalIdPlanet = $(this).parent().parent().attr("id");

            
//        if (  ){
//            
//        
//        }
        
        
    });

    $(this).on("click", "#add-tag-btn", function(event) {
        event.preventDefault();
//        alert("pre ajax");
        /*var newTag = $("input:text",this).val();
         alert("aggiungi al db il tag: "+newTag);
         $("#tags-container .controls").append("<span class='badge badge-info'>"+newTag+"</span>");*/
    });

    $(this).on("click", "#popover_content_wrapper .close", function() {

        $popover.popover('toggle');
    });

    $(this).on("click", ".remove-tag", function(e) {
        e.preventDefault();

        var tag = $(this).parent().attr("id");
        var that = this;
//        alert("rimuovo tag: " + tag + " in " + globalIdPlanet);

        $.post("/deleteTagServlet", {// TODO: gestione tag cancellazione
            editingPlanetId: globalIdPlanet,
            tagId: tag
        }).done(function(data) {
//            alert("Tutto Ok rimozione:" + data + " - this:" + $(that).html());

            $(that).parent().remove();
        });
    });

    /** Gestione della griglia degli universi/pianeti **/

    // suggerimento per eliminare
//    $(".delete-drag-drop").popover();
    $(".delete-drag-drop").tooltip();
    $(".universe-avatar:not(+ .universe-avatar-locked, .universe-avatar-new)").tooltip({
        delay: {show: 1500, hide: 0},
        title: "Trascina l'universo nel cestino per eliminarlo"
    });

    if ($("#universe-selection").length) {


        $("#universe-selection li").draggable({
            handle: ".universe-avatar",
            cursor: "move",
            opacity: 0.7,
            scroll: false,
            revert: "invalid",
            revertDuration: 500,
            appendTo: "body"
        });

        $("#universe-delete").droppable({
            activeClass: "droppable-hover",
            hoverClass: "ui-state-active",
            drop: function(event, ui) {

                var universeTitle = $("h4", ui.draggable).text();
                $("#myModalLabel").text("Conferma eliminazione");
                $("#myModal .modal-body p").html("Vuoi cancellare l'Universo <strong>" + universeTitle + "</strong> ?");
                $('#myModal').modal('show');

                $("#delete-confirm").click(function() {

                    var idUniverse = $("input[name=editingUniverseId]", ui.draggable).val();
                    $.post("/deleteUniverseServlet", {
                        u: idUniverse
                    }).done(function(data) {
                        setTimeout(function() {
                            $(ui.draggable).toggle("explode", {}, 1500);
                            $(ui.draggable).remove();
                        }, 500);
                    });

                });
                $("#delete-cancel").click(function() {
                    //alert(ui.draggable.toString());
                    $("#universe-selection li").animate({
                        left: 0,
                        top: 0
                    });
                    /*
                     $(ui.draggable).draggable("option", "revert", true);
                     setTimeout(function() {
                     $("ui.draggable").draggable("option", "revert", "invalid");
                     }, 1000);*/
                });

            },
            over: function(event, ui) {
                $("button", this).css('zIndex', 20).show();
                //$( ui.draggable ).effect( "size", { to: { width: 50, height: 50 } }, 0 );
            },
            tolerance: 'pointer'
        });

        $("#universe-selection li").disableSelection();
//        $(".universe-avatar-new").parent().parent().parent().draggable("option", "disabled", true); // disabilitazione del drop di "crea un nuovo universo"
        /*
         $(".universe-avatar button").click(function(){
         alert("Creo un nuovo universo, redirect in corso...");
         window.location.replace("/firstStepServlet");
         });
         
         $(".edit-universe").click(function(){
         alert($(this).parent().parent().find("div").attr("id"));
         });
         */

    }

    // $("#connectionModal").text("Conferma eliminazione");
    // $("#connectionModal .modal-body p").html("Vuoi cancellare l'Universo <strong>" + universeTitle + "</strong> ?");
    // $('#connectionModal').modal('show');

    /*$("#delete-confirm").click(function() {
     
     var idUniverse = $("div", ui.draggable).attr("id");
     
     $.post("/deleteUniverseServlet", {
     u : idUniverse
     }).done(function(data) {
     alert("Tutto Ok:" + data);
     setTimeout(function() {
     $(ui.draggable).toggle("explode", {}, 1500);
     $(ui.draggable).remove();
     }, 500);
     });
     
     
     
     });*/


    function enableDraggablePlanets() {

        if ($("#planet-selection").length) {
            $("#planet-selection li").draggable({
                handle: ".planet-avatar",
                cursor: "move",
                opacity: 0.7,
                scroll: false,
                revert: "invalid",
                revertDuration: 500,
                appendTo: "body",
                cancel: false
            });

            $("#planet-delete").droppable({
                activeClass: "droppable-hover",
                hoverClass: "ui-state-active",
                drop: function(event, ui) {
                    var universeTitle = $("h4", ui.draggable).text();
                    $("#myModalLabel").text("Conferma eliminazione");
                    $("#myModal .modal-body p").html("Vuoi cancellare il Pianeta <strong>" + universeTitle + "</strong> ?");
                    $('#myModal').modal('show');

                    deletingPlanet = ui.draggable;

                    $("#delete-confirm").click(function() {

                        var idPlanet = $(deletingPlanet).attr("id");

//                        alert("Pianeta da cancellare:" + idPlanet);
                        $.post("/deletePlanetServlet", {
                            p: idPlanet
                        }).done(function(data) {
//                            alert("Pianeta cancellato:" + data);
                            setTimeout(function() {
                                $(deletingPlanet).toggle("explode", {}, 1500);
                                $(deletingPlanet).remove();
                            }, 500);

                            jsPlumb.remove("endpoint-" + idPlanet);

                            planetsChanged = true;
                            $("#tab-step2").click();

                        });

                    });
                    $("#delete-cancel").click(function() {
                        //alert(ui.draggable.toString());
                        $("#planet-selection li").animate({
                            left: 0,
                            top: 0
                        });
                        /*
                         $(ui.draggable).draggable("option", "revert", true);
                         setTimeout(function() {
                         $("ui.draggable").draggable("option", "revert", "invalid");
                         }, 1000);*/
                    });

                },
                over: function(event, ui) {
                    $("button", this).css('zIndex', 20).show();
                    //$( ui.draggable ).effect( "size", { to: { width: 50, height: 50 } }, 0 );
                },
                tolerance: 'pointer'
            });

            $("#planet-selection li").disableSelection();

            $(".planet-avatar button.edit-planet").click(function() {
                if (!$("#planet-selection li").is('.ui-draggable-dragging')) {
//                    alert("Sto modificando il pianeta " + $(this).parent().parent().attr("id"));
                    globalIdPlanet = $(this).parent().parent().attr("id");

                    $.get("/secondStepServlet", {
                        editingPlanetId: globalIdPlanet,
                        editingUniverseId: globalIdUniverse
                    }).done(function(data) {
                        //alert("Tutto Ok:" + data);

                        var obj = $.parseJSON(data);
                        var firstRow = obj.firstRow;
                        var secondRow = obj.secondRow;
                        var thirdRow = obj.thirdRow;
                        var shortLabel = obj.shortLabel;
                        var descriptionPlanet = obj.descriptionPlanet;

                        var tags = "";

//                        alert(data);
                        $('#firstLine').val(firstRow);
                        $('#firstLine').keyup();
                        $('#secondLine').val(secondRow);
                        $('#secondLine').keyup();
                        $('#thirdLine').val(thirdRow);
                        $('#thirdLine').keyup();
                        $('#labelPlanet').val(shortLabel);
                        $('#labelPlanet').keyup();
                        $('#descPlanet').val(descriptionPlanet);




                        $.each(obj.arrayTag, function(x, tag) {
                            tags += "<span id=\"" + tag.idTag + "\" class=\"badge badge-info\">" + tag.tagValue + " <a href=\"#\" class=\"remove-tag\"><i class=\"icon-remove\"></i></a></span>";
                        });

                        $("#tags-container").find("div").html(tags);
                        $("#tags-container").find("div").append("<a href=\"#\" id=\"add-tag\"><span class=\"badge badge-success\"><i class=\"icon-plus icon-white\"></i></span></a>");
                        planetSelected = true;

                        $("#tab-step22").click();
                    });

                }

            });
            $(".planet-avatar button.new-planet").click(function(e) {
                e.preventDefault();
//                alert("Sto creando un nuovo pianeta");
                if (!$("#planet-selection li").is('.ui-draggable-dragging')) {

                    if ($("#planet-selection li").length - 1 === 20) {
                        $("#max-planets-error").show();
                        $('html, body').animate({
                            scrollTop: $("#max-planets-error").offset().top
                        }, 1000);
                        return 0;
                    }

                    globalIdPlanet = $(this).parent().parent().attr("id");
//                    alert(globalIdPlanet);
                    
                    $.get("/secondStepServlet", {
                        editingPlanetId: globalIdPlanet,
                        editingUniverseId: globalIdUniverse
                    }).done(function(data) {

                        var obj = $.parseJSON(data);
                        var firstRow = obj.firstRow;
                        var secondRow = obj.secondRow;
                        var thirdRow = obj.thirdRow;
                        var shortLabel = obj.shortLabel;
                        var descriptionPlanet = obj.descriptionPlanet;

                        var tags = "";

                        globalIdPlanet = obj.idPlanet;
//                        alert("modificato " + globalIdPlanet);
                        $('#firstLine').val(firstRow);
                        $('#firstLine').keyup();
                        $('#secondLine').val(secondRow);
                        $('#secondLine').keyup();
                        $('#thirdLine').val(thirdRow);
                        $('#thirdLine').keyup();
                        $('#labelPlanet').val(shortLabel);
                        $('#labelPlanet').keyup();
                        $('#descPlanet').val(descriptionPlanet);

                        $("#tags-container").find("div").html(tags);
                        $("#tags-container").find("div").append("<a href=\"#\" id=\"add-tag\"><span class=\"badge badge-success\"><i class=\"icon-plus icon-white\"></i></span></a>");

                        planetSelected = true;
                        planetsChanged = true;
                        $("#tab-step2").click();

                        $("#tab-step22").click();
                    });

                }

            });

        }

        $(".ui-state-disabled").draggable("option", "disabled", true);

    }




    $("#to-content-button").click(function() { // TODO: mettere metodo .on!!!
        $("#tab-step23").click();


    });

    /** Ricerca universo**/
    $('#universe-search').keyup(function(event) {
        var search_text = $(this).val();
        var rg = new RegExp(search_text, 'i');
        $('#universe-selection li h4').each(function() {
            if ($.trim($(this).html()).search(rg) == -1) {
                $(this).parent().parent().hide("slow");
            } else {
                $(this).parent().parent().show("slow");
            }
        });
    });
    /** Ricerca pianeta **/
    $('#planet-search').keyup(function(event) {
        var search_text = $(this).val();
        var rg = new RegExp(search_text, 'i');
        $('#planet-selection li h4').each(function() {
            if ($.trim($(this).html()).search(rg) == -1) {
                $(this).parent().fadeOut("slow");
            } else {
                $(this).parent().fadeIn("slow");
            }
        });
    });
    // tasto clear
    $('#planet-clear').click(function() {
        $('#planet-search').val('');
        $('#planet-selection li').each(function() {
            $(this).fadeIn("slow");
        });
    });

    var charFirstLine = 0;
    var charSecondLine = 0;
    var charThirdLine = 0;
    var charPreview = 0;
    var lastValFirstLine;
    var lastValSecondLine;
    var lastValThirdLine;
    var lastValPreview;

    // per l'anteprima può essere utile un listener del genere
    $('#firstLine').keyup(function() {
        //console.log("dimensione: ", $(this).width());
        charFirstLine = $(this).val().length;
        if (charFirstLine < 12) {
            lastValFirstLine = $(this).val();
            $('.planetBig-preview .line1').text(lastValFirstLine);
            $(this).tooltip('destroy');
        } else {
            $(this).val(lastValFirstLine);
            $(this).tooltip({
                placement: 'bottom',
                trigger: 'manual'
            });
            var that = this;
            $(this).tooltip("show");
            setTimeout(function() {
                $(that).tooltip("destroy");
            }, 4000);
        }
    });
    $('#secondLine').keyup(function() {
        charSecondLine = $(this).val().length;
        if (charSecondLine < 12) {
            lastValSecondLine = $(this).val();
            $('.planetBig-preview .line2').text(lastValSecondLine);
            $(this).tooltip('destroy');
        } else {
            $(this).val(lastValSecondLine);
            $(this).tooltip({
                placement: 'bottom',
                trigger: 'manual'
            });
            var that = this;
            $(this).tooltip("show");
            setTimeout(function() {
                $(that).tooltip("destroy");
            }, 4000);
        }
    });
    $('#thirdLine').keyup(function() {
        charThirdLine = $(this).val().length;
        if (charThirdLine < 11) {
            lastValThirdLine = $(this).val();
            $('.planetBig-preview .line3').text(lastValThirdLine);
            $(this).tooltip('destroy');
        } else {
            $(this).val(lastValThirdLine);
            $(this).tooltip({
                placement: 'bottom',
                trigger: 'manual'
            });
            var that = this;
            $(this).tooltip("show");
            setTimeout(function() {
                $(that).tooltip("destroy");
            }, 4000);
        }
    });

    $('#labelPlanet').keyup(function() {
        charPreview = $(this).val().length;
        if (charPreview < 30) {
            lastValPreview = $(this).val();
            $('.planetSmall-preview p').text(lastValPreview);
        } else {
            $(this).val(lastValPreview);
        }
    });

    // hack agli input type=file
    /*
     $('input[id=file]').change(function() {
     $('#pretty-input').val($(this).val().replace("C:\\fakepath\\", ""));
     });
     /*
     
     // per disabilitare gli accordion usa un controllo qui, per fare l'overriding usa:
     /*$('#myLink').click(function(e) {
     e.preventDefault();
     //do other stuff when a click happens
     });*/

    // Initialize the jQuery File Upload widget:
    //$('#fileupload').fileupload();

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadServlet',
        formData: {happiness: '1'}
    });

    $('#fileupload2').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadAudioVideoServlet',
        formData: {happiness: '1'}
    });
    $('#fileupload3').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadServlet',
        formData: {happiness: '0'}
    });
    $('#fileupload4').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/UploadAudioVideoServlet',
        formData: {happiness: '0'}
    });


// Load existing files:
//    $('#fileupload2').each(function() {
//        var that = this;
//        $.getJSON(this.action, function(result) {
//            if (result && result.length) {
//                $(that).fileupload('option', 'done')
//                        .call(that, null, {result: result});
//            }
//        });
//    });
    // Load existing files:
//    $('#fileupload').each(function () {
//        var that = this;
//        $.getJSON(this.action, function (result) {
//            alert();
//            if (result && result.length) {
//                $(that).fileupload('option', 'done')
//                    .call(that, null, {result: result});
//            }
//        });
//    });





    /*
     *  This file contains the JS that handles the first init of each jQuery demonstration, and also switching
     *  between render modes.
     */
    jsPlumb.bind("ready", function() {

        //jsPlumb.DemoList.init();

        // chrome fix.
        document.onselectstart = function() {
            return false;
        };

        // render mode
        var resetRenderMode = function(desiredMode) {
            var newMode = jsPlumb.setRenderMode(desiredMode);
//            $(".rmode").removeClass("selected");
//            $(".rmode[mode='" + newMode + "']").addClass("selected");
//
//            $(".rmode[mode='canvas']").attr("disabled", !jsPlumb.isCanvasAvailable());
//            $(".rmode[mode='svg']").attr("disabled", !jsPlumb.isSVGAvailable());
//            $(".rmode[mode='vml']").attr("disabled", !jsPlumb.isVMLAvailable());

            jsPlumbDemo.init();
        };
        resetRenderMode(jsPlumb.SVG);

    });


    var happyImageSet = [];
    var sadImageSet = [];
    var planetsObjs = [];
    function getPlanetsReport(async) {

        var flag = false;
        $.ajax({
            async: async,
            type: 'GET',
            data: {selectedUniverse: ""},
            url: '/AdminUniverseServlet'
        }).done(function(jsonPlanets) {

            var obj = $.parseJSON(jsonPlanets);
            var htmlPlanets = "";
            planetsObjs.length = 0;
            happyImageSet.length = 0;
            sadImageSet.length = 0;
            $.each(obj, function(x) {

                var happyPhotos = [];
                var sadPhotos = [];
                var planetTags = [];

                $.each(this["pathPhotoHappy"], function(i) {
                    happyPhotos.push(this);
                });
                $.each(this["pathPhotoSad"], function(i) {
                    sadPhotos.push(this);
                });
                $.each(this["tags"], function(i) {
                    planetTags.push(this);
                });
                var imageColumnHtml = "";
                if (happyPhotos.length !== 0)
                    imageColumnHtml += "<button class=\"btn btn-mini btn-success set-happy\"><i></i></button> ";
                if (sadPhotos.length !== 0)
                    imageColumnHtml += "<button class=\"btn btn-mini btn-danger set-sad\"><i></i></button>";

                var audioColumnHtml = "";
                var videoColumnHtml = "";
                if (this['audioHappyPath'] !== "") {
                    audioColumnHtml += "<button class=\"btn btn-mini btn-success set-happy\"><i></i></button> ";
                }

                if (this['audioSadPath'] !== "") {
                    audioColumnHtml += "<button class=\"btn btn-mini btn-danger set-sad\"><i></i></button>";
                }

                if (this['videoHappyPath'] !== "") {
                    videoColumnHtml += "<button class=\"btn btn-mini btn-success set-happy\"><i></i></button> ";
                }

                if (this['videoSadPath'] !== "") {
                    videoColumnHtml += "<button class=\"btn btn-mini btn-danger set-sad\"><i></i></button>";
                }

                if (videoColumnHtml === "") {
                    videoColumnHtml = "<span class=\"badge badge-important\"><i class=\"icon-remove icon-white\"></i></span>";
                }
                if (audioColumnHtml === "") {
                    audioColumnHtml = "<span class=\"badge badge-important\"><i class=\"icon-remove icon-white\"></i></span>";
                }
                if (imageColumnHtml === "") {
                    imageColumnHtml = "<span class=\"badge badge-important\"><i class=\"icon-remove icon-white\"></i></span>";
                }

                var currentPlanetObj = {
                    idPlanet: this['idPlanet'],
                    label: this['shortLabel'],
                    happyImageSet: happyPhotos,
                    happyImageSetDesc: this['descriptionPhotoHappy'],
                    sadImageSet: sadPhotos,
                    sadImageSetDesc: this['descriptionPhotoSad'],
                    happyAudio: this['audioHappyPath'],
                    happyAudioTitle: this["audioHappyTitle"],
                    happyAudioDesc: this["audioHappyDescription"],
                    sadAudio: this['audioSadPath'],
                    sadAudioTitle: this["audioSadTitle"],
                    sadAudioDesc: this["audioSadDescription"],
                    happyVideo: this['videoHappyPath'],
                    happyVideoTitle: this["videoHappyTitle"],
                    happyVideoDesc: this["videoHappyDescription"],
                    sadVideo: this['videoSadPath'],
                    sadVideoTitle: this["videoSadTitle"],
                    sadVideoDesc: this["videoSadDescription"],
                    info: this['infoPlanet'],
                    emotionalFilter: this['emotionalFilter'],
                    tags: planetTags
                };
                planetsObjs.push(currentPlanetObj);

                htmlPlanets += "<tr id=planet-" + this['idPlanet'] + ">";
                htmlPlanets += "<td><p><strong>Titolo completo:</strong> " + htmlEncode(this['shortLabel']) + "</p><p><strong>Titolo prima riga: </strong>" + htmlEncode(this['titolo1']) + "<br /><strong>Titolo seconda riga: </strong>" + htmlEncode(this['titolo2']) + "<br /><strong>Titolo terza riga: </strong>" + htmlEncode(this['titolo3']) + "</p></td>";
                htmlPlanets += "<td class=\"column-image\">" + imageColumnHtml + "</td>";
                htmlPlanets += "<td class=\"column-audio\">" + audioColumnHtml + "</td>";
                htmlPlanets += "<td class=\"column-video\">" + videoColumnHtml + "</td>";
                htmlPlanets += "<td><button class=\"btn btn-info view-info\"><i class=\"icon-info-sign icon-white\"></i></button></td>";
                htmlPlanets += "</tr>";
            });
            if (htmlPlanets !== "")
                $('#step4 table tbody').html(htmlPlanets);
            $("#tot-planets strong").text(obj.length);
            flag = true;
//            enableAdminController(); // da chiamare una volta sola!
        });
        return flag;
    }

    $("#step4 table tbody").on("click", ".set-happy", function(e) {
        e.preventDefault();
        var type = getRealIdFromFake($(this).parent().attr("class"));
        var idPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
        var position = findIdPlanetInPlanetObjs(idPlanet);
//            alert(position);
        var writeHtml = "";
        switch (type)
        {
            case "image":
                $("#adminModalImageViewLabel").html("Immagini felici");
                // carico lista immagini
                var description = planetsObjs[position].happyImageSetDesc;
//                    alert("description lunga: "+description.length);
                if (description.length <= 1) {
//                        alert("è vuota");
                    description = "- Nessuna descrizione fornita -";
                }
                $.each(planetsObjs[position].happyImageSet, function(i) {
                    if (i == 0)
                        writeHtml += "<div class=\"active item\"><img src=\"Universes/" + this + "\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>" + description + "</p></div></div>";
                    else
                        writeHtml += "<div class=\"item\"><img src=\"Universes/" + this + "\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>" + description + "</p></div></div>";

                });
                $('#image-carousel .carousel-inner').html(writeHtml);
                $('#adminModalImageView').modal('show');
                break;
            case "video":
                // nella finestra modale nasconde il player audio e mostra quello video
                $("#jquery_jplayer_2").hide();
                $("#jp_container_2").hide();
                $("#jp_container_1").show();

                $("#adminModalMultimediaViewLabel").html("Video felice ");
                // carico il video
                $("#jquery_jplayer_1").jPlayer("clearMedia");
                $("#jquery_jplayer_1").jPlayer("setMedia", {
                    m4v: "/Universes/" + planetsObjs[position].happyVideo
                });
                $("#jp_container_1 div.jp-title h4").html(planetsObjs[position].happyVideoTitle);
                $("#jp_container_1 div.jp-title li").html(planetsObjs[position].happyVideoDesc);

                $('#adminModalMultimediaView').modal('show');
                break;
            case "audio":
                // nella finestra modale nasconde il player video e mostra quello audio
                $("#jquery_jplayer_2").show();
                $("#jp_container_2").show();
                $("#jp_container_1").hide();

                $("#adminModalMultimediaViewLabel").html("Audio felice ");

                $("#jquery_jplayer_2").jPlayer("clearMedia");
                $("#jquery_jplayer_2").jPlayer("setMedia", {
                    mp3: "/Universes/" + planetsObjs[position].happyAudio
                });

                $("#jp_container_2 div.jp-title h4").html(planetsObjs[position].happyAudioTitle);
                $("#jp_container_2 div.jp-title li").html(planetsObjs[position].happyAudioDesc);

                $('#adminModalMultimediaView').modal('show');
                break;
        }
    });
    $("#step4 table tbody").on("click", ".set-sad", function(e) {
        e.preventDefault();
        var type = getRealIdFromFake($(this).parent().attr("class"));
        var idPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
        var position = findIdPlanetInPlanetObjs(idPlanet);
//            alert(position);
        var writeHtml = "";
        switch (type)
        {
            case "image":
                var description = planetsObjs[position].sadImageSetDesc;
//                alert("description: " + description);
//                alert("description lunga: " + description.length);
                if (description.length <= 1) {
//                        alert("è vuota");
                    description = "- Nessuna descrizione fornita -";
                }

                $("#adminModalImageViewLabel").html("Immagini non felici");
                // carico lista immagini

                $.each(planetsObjs[position].sadImageSet, function(i) {
                    if (i == 0)
                        writeHtml += "<div class=\"active item\"><img src=\"Universes/" + this + "\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>" + description + "</p></div></div>";
                    else
                        writeHtml += "<div class=\"item\"><img src=\"Universes/" + this + "\" /><div class=\"carousel-caption\"><h4>Descrizione</h4><p>" + description + "</p></div></div>";

                });
                $('#image-carousel .carousel-inner').html(writeHtml);
                $('#adminModalImageView').modal('show');
                break;
            case "video":
                // nella finestra modale nasconde il player audio e mostra quello video
                $("#jquery_jplayer_2").hide();
                $("#jp_container_2").hide();
                $("#jp_container_1").show();

                $("#adminModalMultimediaViewLabel").html("Video non felice ");
                // carico il video
                $("#jquery_jplayer_1").jPlayer("clearMedia");
                $("#jquery_jplayer_1").jPlayer("setMedia", {
                    m4v: "/Universes/" + planetsObjs[position].sadVideo
                });
                $("#jp_container_1 div.jp-title h4").html(planetsObjs[position].sadVideoTitle);
                $("#jp_container_1 div.jp-title li").html(planetsObjs[position].sadVideoDesc);

                $('#adminModalMultimediaView').modal('show');
                break;
            case "audio":
                // nella finestra modale nasconde il player video e mostra quello audio
                $("#jquery_jplayer_2").show();
                $("#jp_container_2").show();
                $("#jp_container_1").hide();

                $("#adminModalMultimediaViewLabel").html("Audio non felice ");

                $("#jquery_jplayer_2").jPlayer("clearMedia");
                $("#jquery_jplayer_2").jPlayer("setMedia", {
                    mp3: "/Universes/" + planetsObjs[position].sadAudio
                });

                $("#jp_container_2 div.jp-title h4").html(planetsObjs[position].sadAudioTitle);
                $("#jp_container_2 div.jp-title li").html(planetsObjs[position].sadAudioDesc);

                $('#adminModalMultimediaView').modal('show');
                break;
        }
    });
    $("#step4 table tbody").on("click", ".view-info", function(e) {
        var idPlanet = getRealIdFromFake($(this).parent().parent().attr("id"));
        var position = findIdPlanetInPlanetObjs(idPlanet);
//            alert("fratello "+$(this).next().length+", popover: "+$(this).next().hasClass("popover"));
        if ($(this).next().length && $(this).next().hasClass("popover")) {
            $(this).popover('destroy');
        } else {
            $(this).popover({
                placement: "left",
                title: "Descrizione",
                content: htmlEncode(planetsObjs[position].info)
            });
            $(this).popover('show');
        }
    });

    /**
     * permette di stoppare il video se si clicca sul bottone close mentre è in esecuzione
     */
    $("#admin-close-video-button").on("click", function(e) {
        e.preventDefault();
        $("#jquery_jplayer_1").jPlayer("stop");
        $("#jquery_jplayer_2").jPlayer("stop");
    });
    if ($("#jquery_jplayer_1").length) {
        $("#jquery_jplayer_1").jPlayer({
            swfPath: "js",
            supplied: "m4v",
            size: {
                width: "640px",
                height: "360px",
                cssClass: "jp-video-360p"
            },
            cssSelectorAncestor: '#jp_container_1',
            smoothPlayBar: true,
            keyEnabled: true
        });
    }

    if ($("#jquery_jplayer_2").length) {
        $("#jquery_jplayer_2").jPlayer({
            swfPath: "js",
            supplied: "mp3",
            wmode: "window",
            cssSelectorAncestor: '#jp_container_2',
            smoothPlayBar: true,
            keyEnabled: true
        });
    }

    $("#tab-step4").click(function() {
        var validScreen = false;
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step22").parent().hasClass("active") && checkSecondStepFields()) {
            sendPlanetData(false, false);
            validScreen = true;
        }
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step23").parent().hasClass("active")) {
            var descChecked = checkContentDescAndSend(false, null, false);
            if (descChecked !== false)
                validScreen = true;
        }
        if ($("#tab-step1").parent().hasClass("active")) {
            var fieldCheckAndSave = getPlanets(false);
            if (fieldCheckAndSave)
                validScreen = true;
        }

        if ($("#tab-step3").parent().hasClass("active") || $("#tab-step5").parent().hasClass("active") || ($("#tab-step2").parent().hasClass("active") && $("#tab-step21").parent().hasClass("active")))
            validScreen = true;

        if (!validScreen)
            return validScreen;

        getPlanetsReport(true);
    });

    $("#tab-step1").click(function() {
        var validScreen = false;
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step22").parent().hasClass("active") && checkSecondStepFields()) {
            sendPlanetData(false,false);
            validScreen = true;
        }
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step23").parent().hasClass("active")) {
            var descChecked = checkContentDescAndSend(false, null, false);
            if (descChecked !== false)
                validScreen = true;
        }
        if ($("#tab-step4").parent().hasClass("active") || $("#tab-step3").parent().hasClass("active") || $("#tab-step5").parent().hasClass("active") || ($("#tab-step2").parent().hasClass("active") && $("#tab-step21").parent().hasClass("active")))
            validScreen = true;

        if (!validScreen)
            return validScreen;
    });

    $("#tab-step5").click(function() {
        var validScreen = false;
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step22").parent().hasClass("active") && checkSecondStepFields()) {
            sendPlanetData(false, false);
            validScreen = true;
        }
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step23").parent().hasClass("active")) {
            var descChecked = checkContentDescAndSend(false, null, false);
            if (descChecked !== false)
                validScreen = true;
        }
        if ($("#tab-step1").parent().hasClass("active")) {
          var fieldCheckAndSave = getPlanets(false);
            if (fieldCheckAndSave)
                validScreen = true;
        }

        if ($("#tab-step4").parent().hasClass("active") || $("#tab-step3").parent().hasClass("active") || ($("#tab-step2").parent().hasClass("active") && $("#tab-step21").parent().hasClass("active")))
            validScreen = true;

        if (!validScreen)
            return validScreen;
    });

    $("#tab-step3").click(function() {
//        planetsChanged = true;
        var validScreen = false;
//        if ($("#tab-step1").parent().hasClass("active")){
//            validScreen = true;
//        }

        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step22").parent().hasClass("active") && checkSecondStepFields()) {
            
            validScreen = true;
        }
        if ($("#tab-step2").parent().hasClass("active") && $("#tab-step23").parent().hasClass("active")) {
            var descChecked = checkContentDescAndSend(false, null, false);
            if (descChecked !== false)
                validScreen = true;
        }
        if ($("#tab-step1").parent().hasClass("active") ) {
            var fieldCheckAndSave = getPlanets(false);
            if (fieldCheckAndSave)
                validScreen = true;
        }

        // tutti gli altri che non richiedono check
        if ($("#tab-step4").parent().hasClass("active") || $("#tab-step5").parent().hasClass("active") || ($("#tab-step2").parent().hasClass("active") && $("#tab-step21").parent().hasClass("active")))
            validScreen = true;
        
        if (!validScreen)
            return validScreen;
        else
            sendPlanetData(false,false);

    });

    var planetsChanged = false;
    $("#tab-step3").on('shown', function(e) {

        if (planetsChanged) {
            generateGraph(nodes);

            if (nodes.length > 0) {


                $.each(g.nodes, function(i) {
                    var oBBox = this.shape.getBBox();
                    var opoint = {x: (oBBox.x + oBBox.width / 2) - 30, y: (oBBox.y + oBBox.height / 2) + 30};

                    var fakeid = this.id;
                    fakeid = fakeid.replace("!", "")
                    var planetId = getRealIdFromFake(fakeid);
                    if ($("#" + fakeid) != undefined) {
                        $("#" + fakeid).css("top", opoint.y);
                        $("#" + fakeid).css("left", opoint.x);
                    }
                    $.post("/connectionsServlet", {
                        planetMoved: planetId,
                        setX: Math.round(opoint.x),
                        setY: Math.round(opoint.y)
                    }).done(function(data) {
                        //                  alert("Aggiornata posizione sul db di: " + planetId + " con punto " + x + ", " + y);
                    });
                    //                alert("! "+this.shape.getBBox().x);
                });
            }
            planetsChanged = false;
        }
        jsPlumbDemo.init();
        jsPlumb.repaintEverything();
        connections.length = 0;

//        $("#endpoint-" + this['idPlanet']).css("top", this['y']);
//        $("#endpoint-" + this['idPlanet']).css("left", this['x']);

        $.get("/connectionsServlet", {
        }).done(function(data) {

            var obj = $.parseJSON(data);

//                planetsArray.length = 0;
            automaticAdd = true;
            $.each(obj, function(x) {

                connectPlanet(this['startPlanet'], this['destinationPlanet'], this['r'], this['g'], this['b']);

            });
            automaticAdd = false;

        });


    });


    function sendPlanetData(async, emotionalFileterActive) {
        $.ajax({
            async: async,
            type: 'POST',
            data: {editingPlanetId: globalIdPlanet,
                title1: $('#firstLine').val(),
                title2: $('#secondLine').val(),
                title3: $('#thirdLine').val(),
                shortLabel: $('#labelPlanet').val(),
                description: $('#descPlanet').val()},
            url: '/secondStepServlet'
        }).done(function(data) {
//                alert("Emotional ricevuto: " + data);
            var splitted = data.split("-");
            globalIdPlanet = splitted[0];
            if(emotionalFileterActive){
                
                switch (splitted[1]) {
                    case "1":
                        $("#nonEmotionalContentChoose").click();
                        break;
                    case "2":
                        $("#emotionalContentChoose").click();
                        break;
                    default:
                        emotionalChoosed = false;
                        $("#loading-img").show();
                        $("#planetTabLv2").parent().hide();
                        $("#planetTabLv2-emotional").parent().hide();

                        $("#contentModalLabel").text("Utilizzare il filtro emozionale?");
                        $('#contentModal').modal('show');
                }
            }
            return true;
        });
    }

    var emotionalChoosed = true;
//    Metodo richiamato PRIMA di lanciare il .show() sulla tab appropriata
    $("#tab-step23").click(function() {

        if (planetSelected && checkSecondStepFields()) {
            // globalIdPlanet = $(this).parent().parent().attr("id");

            sendPlanetData(true, true);

        } else {
            return false;
        }
    });

    $("#emotionalContentChoose").click(function() {

        if (!emotionalChoosed) { // se è la prima volta che si è scelto filtro emozionale, registro la scelta sul db
            $.post("/secondStepServlet", {
                editingPlanetId: globalIdPlanet,
                emotionalChoose: "2"
            }).done(function(data) {
//                alert(data);
                emotionalChoosed = true;
            });
        }

        $("#loading-img").fadeOut("fast");
        $("#planetTabLv2").parent().fadeOut("fast");
        $("#planetTabLv2-emotional").parent().fadeIn("slow");

        $("#step231-happy").prepend($("#fileupload-container"));
        $("#fileupload-container").show();

        $("#step232-happy").prepend($("#fileupload-multimedia-container"));
        $("#fileupload-multimedia-container").show();

        $('.files tr.template-download').remove();
        $('.files tr.template-upload').remove();


        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload2').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload2')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '0'},
            url: $('#fileupload3').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload3')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '0'},
            url: $('#fileupload4').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload4')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });

        currentActiveTab = "tab-step231-happy";
        $("#" + currentActiveTab).click();

    });

    $("#nonEmotionalContentChoose").click(function() {

        if (!emotionalChoosed) { // se è la prima volta che si è scelto filtro emozionale, registro la scelta sul db
            $.post("/secondStepServlet", {
                editingPlanetId: globalIdPlanet,
                emotionalChoose: "1"
            }).done(function(data) {
//                alert(data);
                emotionalChoosed = true;
            });
        }

        $("#loading-img").fadeOut("fast");
        $("#planetTabLv2-emotional").parent().fadeOut("fast");
        $("#planetTabLv2").parent().fadeIn("slow");

        $("#step231").prepend($("#fileupload-container"));
        $("#fileupload-container").show();

        $("#step232").prepend($("#fileupload-multimedia-container"));
        $("#fileupload-multimedia-container").show();

        $('.files tr.template-download').remove();
        $('.files tr.template-upload').remove();

        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            data: {happiness: '1'},
            url: $('#fileupload2').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload2')[0]
        }).always(function(result) {
//                alert(result);
            $(this).removeClass('fileupload-processing');

        }).done(function(result) {
//                alert(result);
            $(this).fileupload('option', 'done')
                    .call(this, null, {result: result});
        });
        currentActiveTab = "tab-step231";
        $("#" + currentActiveTab).click();
    });

    function connectPlanet(startPlanet, endPlanet, r, g, b) {
//        alert(startPlanet + " ," + endPlanet);
        var conn = jsPlumb.connect({uuids: ["endpoint-" + startPlanet, "endpoint-" + endPlanet], editable: true});

        conn.setPaintStyle({
            lineWidth: 3,
            strokeStyle: "rgba(" + r + "," + g + "," + b + ",0.5)",
            joinstyle: "round"
                    //outlineColor:transparent,
                    //outlineWidth:7
        });
//        jsPlumb.connect({ source:"endpoint-"+startPlanet, target:"endpoint-"+endPlanet });
    }


    function addEndPointPlanet(compositeIdPlanet) {
        jsPlumb.addEndpoint(compositeIdPlanet,
                {
                    endpoint: "Dot",
                    paintStyle: {fillStyle: "rgba(255,255,255,0.5)", radius: 15},
                    isSource: true,
                    isTarget: true,
                    connector: ["Straight", /*{ stub:[40, 60], gap:10 }*/],
                    connectorStyle: {
                        lineWidth: 3,
                        strokeStyle: "rgba(255,255,255,0.5)",
                        joinstyle: "round",
                    },
                    connectorHoverStyle: {
                        lineWidth: 3,
                        strokeStyle: "rgba(255, 165, 0,0.5)"
                    },
                    dragOptions: {},
                    beforeDrop: function(params) {
                        return updateConnections(params.connection);
                    },
                    maxConnections: -1
                }
        , {anchor: "TopCenter", uuid: compositeIdPlanet});
    }

    var nodes = [];
    function getPlanets(async) {

        if (checkFirstStepFields()) {
            /* get some values from elements on the page: */
            var returnVal = true;
            var $form = $("#first-step-submit"), 
                    nameUniverse = $form.find('input[name="nameUniverse"]').val(), 
                    descUniverse = $form.find('textarea[name="descUniverse"]').val();
            $.ajax({
                async: async,
                type: 'POST',
                data: {n: nameUniverse,
                       d: descUniverse},
                url: '/firstStepServlet'
            }).done(function(data) {
                
                var obj = $.parseJSON(data);
                $('.already-exist', "#nameUniverse-container").fadeOut("slow");
                if (obj.error !== undefined) {
                
                    $("#nameUniverse-container").addClass("error");
                    $('.already-exist', "#nameUniverse-container").fadeIn("slow");
        
                    returnVal = false;
                } else {
                    var planets = "";
                    var planetsEndPoint = "";

                    //resetto il canvas
                    $('#galaxy-connection-container').html("");

                    planetsArray.length = 0;
                    nodes.length = 0;

                    if (g != undefined) {
                        $("#canvas").html("");
                        g.nodes.length = 0;
                    }
//                if(nodes.length > 0){
//                    alert("nodes lungo: "+nodes.length);
//                    deleteAllNodes(nodes);
//                }

                    $.each(obj, function(x) {

                        if (x == 0) {
                            globalIdUniverse = this['idPlanet'];
                        } else {
                            // aggiungi l'id pianeta alla lista di quelli presenti
                            planetsArray.push(this['idPlanet']);

                            nodes.push("!endpoint-" + this['idPlanet']);
//                        alert(nodes[nodes.length-1]);

                            planets += "<li id='" + this['idPlanet'] + "'>";
                            planets += "<div class=\"planet-avatar\">";
                            planets += "<button type=\"button\" class=\"edit-planet\"></button>";
                            planets += "</div>";
                            planets += "<h4 class=\"big-title\">" + htmlEncode(this['shortLabel']) + "</h4>";
                            planets += "</li>";

                            //aggiungo gli endpoint nella sezione connessioni
                            planetsEndPoint += "<div class=\"window\" id=\"endpoint-" + this['idPlanet'] + "\" title=\"" + htmlEncode(this['shortLabel']) + "\">";
                            planetsEndPoint += "<h5>" + htmlEncode(this['shortLabel']) + "</h5>";
                            planetsEndPoint += "</div>";
                            $('#galaxy-connection-container').append(planetsEndPoint);
                            planetsEndPoint = "";
                            // sposta a seconda della posizione in db
                            $("#endpoint-" + this['idPlanet']).css("top", this['y']);
                            $("#endpoint-" + this['idPlanet']).css("left", this['x']);

                            addEndPointPlanet("endpoint-" + this['idPlanet']);
                        }
                    });
                    $('#planet-selection').html(planets);
                    var addPlanetHmtl = "<li id=\"-1\" class=\"ui-state-disabled\" class=\"text-center\">" + "<div class=\"planet-avatar\">" + "<button type=\"button\"></button>" + "<button type=\"button\" class=\"new-planet\"></button>" + "</div>" + "<h4 class=\"big-title\">Crea un pianeta</h4>" + "</li>";
                    $('#planet-selection').append(addPlanetHmtl);
                    enableDraggablePlanets();

                    $('#galaxy-connection-container').append("<div id=\"list\"></div>");

                    if (planets === "") {
                        $("#title-tab-step21 h3, #title-tab-step2 h3").removeClass("hide");
                        $("#title-tab-step21 h3.existing, #title-tab-step21 h3.existing").addClass("hide");
                    } else {
                        $("#title-tab-step21 h3, #title-tab-step2 h3").addClass("hide");
                        $("#title-tab-step21 h3.existing, #title-tab-step2 h3.existing").removeClass("hide");
                    }
                    
                    
                }
            });
            return returnVal;
        } else {
            return false;
        }
    }

    $("#tab-step21").click(function() {
        if (planetSelected && checkSecondStepFields()) {

            $.post("/secondStepServlet", {
                editingPlanetId: globalIdPlanet,
                editingUniverseId: globalIdUniverse,
                title1: $('#firstLine').val(),
                title2: $('#secondLine').val(),
                title3: $('#thirdLine').val(),
                shortLabel: $('#labelPlanet').val(),
                description: $('#descPlanet').val()
            }).done(function(data) { // %%%%%%%%
                var splitted = data.split("-");
                globalIdPlanet = splitted[0];
                //alert("Tutto Ok:" + data);
                planetSelected = false;
                getPlanets(true);
                return true;
            });


        } else {
            return false;
        }
    });

    $("#tab-step21").on('shown', function(e) {
        planetSelected = false;
    });

    $("#tab-step2").click(function(event) {
        event.preventDefault();

        var validScreen = false;

        if ($("#tab-step1").parent().hasClass("active")) {
            var fieldCheckAndSave = getPlanets(false);
            if (fieldCheckAndSave)
                validScreen = true;
        }

        if ($("#tab-step4").parent().hasClass("active") || $("#tab-step3").parent().hasClass("active") || $("#tab-step5").parent().hasClass("active"))
            validScreen = true;

        if (!validScreen)
            return validScreen;


//        return getPlanets(true);
    });

    $("#tab-step22").click(function() {
        hideErrorToContainer($("#firstLine-container"));
        hideErrorToContainer($("#secondLine-container"));
        hideErrorToContainer($("#thirdLine-container"));
        hideErrorToContainer($("#labelPlanet-container"));
        hideErrorToContainer($("#descPlanet-container"));
        if (planetSelected) {
            return true;
        } else {
            return false;
        }
    });

    if ($('#colorpicker1').length) {
        $('#colorpicker1').farbtastic(function(color) {
            $('#colorp1').css({'background-color': color});
            $("#currentColor").val(color);
        });
    }
    if (!$("#title-tab-step1").length && $("#tab-step4").length)
        getPlanetsReport(true);

    $("#submit-universe").click(function(e) {
        e.preventDefault();
        if (isUniverseSubmittable()) { // controllo dei fields (se ci sono abbastanza contenuti per ogni pianeta...)
            $("#publishModal").modal('show');
            $.post("/universePublisher", {
            }).done(function(data) {
                window.location.href = data;
            });
        } else {
            $("#publish-report").show();
        }
    });

    if ($("#publishModal").length)
        $("#publishModal").modal('show');

    var isUniverseSubmittable = function() {
        var valid = true;
        var planetsReport = getPlanetsReport(false);

        if (!planetsReport)
            return false;
        $("#publish-report table tbody").html("");
        if (planetsObjs.length == 0) {
            $("#publish-report table tbody").append("<tr><td colspan=\"2\" class=\"text-error text-center\">Non hai ancora creato nessun pianeta</td></tr>");
            valid = false;
        }

        $.each(planetsObjs, function() {

            if (this.tags.length == 0) {
                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Devi inserire <strong>almeno un tag</strong> nel pianeta.</td></tr>");
                valid = false;
            }

            switch (this.emotionalFilter) {
                case 1:
                    if (this.happyImageSet.length == 0) {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono state caricate <strong>immagini</strong></td></tr>");
                        valid = false;
                    } else
                    if (this.happyImageSetDesc == "") {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non &egrave; stata inserita una <strong>descrizione per le immagini</strong></td></tr>");
                        valid = false;
                    }

                    if (this.happyAudio.length == 0 && this.happyVideo.length == 0) {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti contenuti <strong>video/audio</strong></td></tr>");
                        valid = false;
                    } else {
                        if (this.happyAudio.length != 0) { // inseriti contenuti Audio
                            if (this.happyAudioTitle == "" || this.happyAudioDesc == "") {
                                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti un titolo e/o una descrizione per il <strong>contenuto audio</strong></td></tr>");
                                valid = false;
                            }
                        } else {// inseriti contenuti Video
                            if (this.happyVideoTitle == "" || this.happyVideoDesc == "") {
                                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti un titolo e/o una descrizione per il <strong>contenuto video</strong></td></tr>");
                                valid = false;
                            }
                        }
                    }
                    break;
                case 2:
                    //controllo contenuti felici
                    if (this.happyImageSet.length == 0) {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono state caricate <strong>immagini felici</strong></td></tr>");
                        valid = false;
                    } else
                    if (this.happyImageSetDesc == "") {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non &egrave; stata inserita una descrizione per le <strong>immagini felici</strong></td></tr>");
                        valid = false;
                    }

                    if (this.happyAudio.length == 0 && this.happyVideo.length == 0) {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti contenuti <strong>video/audio felici</strong></td></tr>");
                        valid = false;
                    } else {
                        if (this.happyAudio.length != 0) { // inseriti contenuti Audio
                            if (this.happyAudioTitle == "" || this.happyAudioDesc == "") {
                                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti un titolo e/o una descrizione per il contenuto <strong>audio felice</strong></td></tr>");
                                valid = false;
                            }
                        } else {// inseriti contenuti Video
                            if (this.happyVideoTitle == "" || this.happyVideoDesc == "") {
                                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti un titolo e/o una descrizione per il contenuto <strong>video felice</strong></td></tr>");
                                valid = false;
                            }
                        }
                    }
                    //controllo contenuti tristi
                    if (this.sadImageSet.length == 0) {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono state caricate <strong>immagini non felici</strong></td></tr>");
                        valid = false;
                    } else
                    if (this.sadImageSetDesc == "") {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non &egrave; stata inserita una descrizione per le <strong>immagini non felici</strong></td></tr>");
                        valid = false;
                    }

                    if (this.sadAudio.length == 0 && this.sadVideo.length == 0) {
                        $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti contenuti <strong>video/audio non felici</strong></td></tr>");
                        valid = false;
                    } else {
                        if (this.sadAudio.length != 0) { // inseriti contenuti Audio
                            if (this.sadAudioTitle == "" || this.sadAudioDesc == "") {
                                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti un titolo e/o una descrizione per il contenuto <strong>audio non felice</strong></td></tr>");
                                valid = false;
                            }
                        } else {// inseriti contenuti Video
                            if (this.sadVideoTitle == "" || this.sadVideoDesc == "") {
                                $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non sono stati inseriti un titolo e/o una descrizione per il contenuto <strong>video non felice</strong></td></tr>");
                                valid = false;
                            }
                        }
                    }
                    break;
                default:

                    $("#publish-report table tbody").append("<tr><td>" + htmlEncode(this.label) + "</td><td>Non &egrave; stato inserito <strong>alcun contenuto</strong>.</td></tr>");
                    valid = false;
                    return false;
            }

        });

        return valid;
    };
//    $("#tab-step233-sad").click(function(){
//        var str = $(this).parent().parent().attr("id");
//        alert($(str+" a.active").attr("id"));
//    });
    var g;
    var renderer;
    var layouter;

    var galaxyWidth;
    var galaxyHeight;
    function generateGraph(nodes) {
        galaxyWidth = $('#galaxy-connection-container').width() - 60;
        galaxyHeight = $('#galaxy-connection-container').height() - 40;
//        alert(galaxyWidth + ", " + galaxyHeight);
        /* Showcase of the Bellman-Ford search algorithm finding shortest paths
         from one point to every node */

        g = new Graph();

        /* modify the edge creation to attach random weights */
        /*g.edgeFactory.build = function(source, target) {
         var e = jQuery.extend(true, {}, this.template);
         e.source = source;
         e.target = target;
         e.style.label = e.weight = Math.floor(Math.random() * 10) + 1;
         return e;
         }*/

        /* creating nodes and passing the new renderer function to overwrite the default one */
        $.each(nodes, function(x, val) {
            addNode(val);
        });

//        g.addEdge("Tel Aviv", "Berlin");
//        g.addEdge("Tel Aviv", "New York");
//
//
//        g.addEdge("Berlin", "New York");


        /* layout the graph using the Spring layout implementation */
        layouter = new Graph.Layout.Spring(g);
        renderer = new Graph.Renderer.Raphael('canvas', g, galaxyWidth, galaxyHeight);

//        /* colourising the shortest paths and setting labels */
//        for (e in g.edges) {
//            if (g.edges[e].target.predecessor === g.edges[e].source
//                    || g.edges[e].source.predecessor === g.edges[e].target)
//            {
//                g.edges[e].style.stroke = '#bfa';
//                g.edges[e].style.fill = '#56f';
//            } else {
//                g.edges[e].style.stroke = '#aaa';
//            }
//        }



//  alert(g.nodes['New York'].shape.getBBox());

    }
    function addNode(name) {

        g.addNode(name);
    }
    redraw = function() {
        layouter.layout();
        renderer.draw();
    };
    hide = function(id) {
        g.nodes[id].hide();
    };
    show = function(id) {
        g.nodes[id].show();
    };

    deleteAllNodes = function(n) {
        $.each(n, function(i, val) {
            g.removeNode(val);
        });
    };

});

var prova = function(i) {
//    alert();
//    $(".template-upload[data-idupload=" + i.name + "]").remove();
    $('#uploadErrorModal').modal('show');
};

var getKeys = function(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
    }
    return keys;
};

var printKeys = function(obj) {
    var keys = getKeys(obj);
    var str = "";
    $.each(keys, function() {
        str += this + " = " + obj.error;
    });
//    alert(str);
};